package org.example.ratelimit2.impl;

import org.example.ratelimit2.MyRateLimiter;

public class TokenBucketRateLimiter implements MyRateLimiter {

    private final int capacity;

    private final int generatedPerSecond;

    private long lastTokenTime = System.currentTimeMillis();

    private int currentTokens;

    public TokenBucketRateLimiter(int capacity, int generatedPerSecond) {
        this.capacity = capacity;
        this.generatedPerSecond = generatedPerSecond;
    }

    @Override
    public synchronized boolean tryAcquire() {
        long nowTs = System.currentTimeMillis();
         if (nowTs - lastTokenTime >= 1000) {
            int tokens = (int) ((nowTs - lastTokenTime) / 1000 * generatedPerSecond);
            // 令牌数最多capacity
            currentTokens = Math.min(currentTokens + tokens, capacity);
            lastTokenTime = nowTs;
         }
        if (currentTokens > 0) {
            currentTokens--;
            return true;
        }
        return false;
    }
}
